package com.ic.controller;

import com.ic.base.BaseController;
import com.ic.base.OperatorType;
import com.ic.entity.UserInfo;
import com.ic.service.UserInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: 登录业务控制层
 * Author: spark
 * Date  : 2017/7/17
 * Time  : 14:44.
 */
@Controller
@RequestMapping("/loginController")
public class LoginController extends BaseController {

	@Resource
	private UserInfoService userInfoService;

	/**
	 * 验证用户信息是否存在，如果存在登录系统
	 *
	 * @param userInfo 用户信息
	 * @return Map
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/checkUserInfo")
	@ResponseBody
	public Map checkUserInfo(UserInfo userInfo) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		UserInfo returnUserInfo = userInfoService.checkUserInfo(userInfo);
		if (returnUserInfo != null) {
			session.setAttribute("userInfo", returnUserInfo);
			return success(new HashMap<>(), OperatorType.SELECT, null);
		} else {
			return failed(new HashMap<>(), OperatorType.SELECT, null);
		}
	}

	/**
	 * 用户登出系统
	 *
	 * @return Map
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/loginOut")
	@ResponseBody
	public Map loginOut() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		session.invalidate();
		return success(new HashMap<>(), OperatorType.SELECT, null);
	}

	/**
	 * 修改管理员密码
	 *
	 * @param userInfo    用户信息
	 * @param newPassword 新密码
	 * @return Map
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/modifyPassword")
	@ResponseBody
	public Map modifyPassword(UserInfo userInfo, String newPassword) {
		return success(userInfoService.updatePassword(userInfo, newPassword), OperatorType.UPDATE, null);
	}
}
